﻿using ServiceWeb.DBGateway;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Models.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UtilsBase;
using System.Security.Cryptography;
using System.Data.SqlTypes;
using UtilsORM;
using UtilsORM.MySqlData;
using UtilsCache;
using System.Data;
using Masuit.Tools.Database;

namespace ServiceWeb.DBGateway
{
    public class DBIotDeviceLinkageCondition
    {

        public void setLinkageConditionValue(string pguid, int modelno, string val)
        {
            EFYihongIotContext ef = new EFYihongIotContext();
            // iot_device_linkage linkage = ef.iot_device_linkage.Where(x => x.l_p_guid == pguid).FirstOrDefault();

            iot_device_linkage_condition condition = (from l in ef.iot_device_linkage
                                                      join c in ef.iot_device_linkage_condition on l.l_guid equals c.lc_l_guid
                                                      where l.l_p_guid == pguid && c.lc_p_model_no == modelno
                                                      select c).FirstOrDefault();


            ef.iot_device_linkage_condition.Where(c => c.lc_id == condition.lc_id).ExecuteUpdate(c =>
            c.SetProperty(c => c.lc_value, val));


            //删除缓存
            UtilMemoryCacheHelper.remove("iot_device_linkage_condition" + condition.lc_l_guid);
        }

        public List<iot_device_linkage_condition> getLinkageConditionValue(string pguid,string modelno)
        {
            EFYihongIotContext ef = new EFYihongIotContext();
            // iot_device_linkage linkage = ef.iot_device_linkage.Where(x => x.l_p_guid == pguid).to;

            var sql = (from l in ef.iot_device_linkage
                       join c in ef.iot_device_linkage_condition on l.l_guid equals c.lc_l_guid
                       where l.l_p_guid == pguid
                       select c);

            if(!string.IsNullOrEmpty(modelno))
            {
                string[] nos = modelno.Split(',');
                List<int> arrs = new List<int>();   //用来存放将字符串转换成int[]
                for (int i = 0; i < nos.Length; i++)
                {
                    if (!string.IsNullOrEmpty(nos[i]))
                    {
                        arrs.Add(int.Parse(nos[i]));
                    }
                }
                if (arrs.Count > 0)
                {
                    sql = sql.Where(c => arrs.Contains((int)c.lc_p_model_no));
                }
            }
           return sql.ToList();
            // return ef.iot_device_linkage_condition.Where(c => c.lc_l_guid == linkage.l_guid).ToList();
        }


        public DataTable getLinkageConditionValue_dt(string pguid, string modelno)
        {
            EFYihongIotContext ef = new EFYihongIotContext();
          
            var sql = (from l in ef.iot_device_linkage
                       join c in ef.iot_device_linkage_condition on l.l_guid equals c.lc_l_guid
                       where l.l_p_guid == pguid
                       select c);

            if (!string.IsNullOrEmpty(modelno))
            {
                string[] nos = modelno.Split(',');
                List<int> arrs = new List<int>();   //用来存放将字符串转换成int[]
                for (int i = 0; i < nos.Length; i++)
                {
                    if (!string.IsNullOrEmpty(nos[i]))
                    {
                        arrs.Add(int.Parse(nos[i]));
                    }
                }
                if (arrs.Count > 0)
                {
                    sql = sql.Where(c => arrs.Contains((int)c.lc_p_model_no));
                }
            }
            return sql.Select(c=>new {c.lc_p_model_no,c.lc_value }).ToDataTable();
        }



        public bool del(List<iot_device_linkage> iot_Device_Linkages)
        {
            foreach (iot_device_linkage iot_Device_Linkage in iot_Device_Linkages)
            {
                MySqlYihongFileServer utilsMySql = new MySqlYihongFileServer();
                utilsMySql.Db.BeginTran();
                utilsMySql.Db.Deleteable<iot_device_linkage>().Where(c => c.l_guid == iot_Device_Linkage.l_guid).ExecuteCommand();
                utilsMySql.Db.Deleteable<iot_device_linkage_condition>().Where(c => c.lc_l_guid == iot_Device_Linkage.l_guid).ExecuteCommand();
                utilsMySql.Db.CommitTran();
            }
            return true;
        }

        public bool saveAll(MagerLoginInfo LoginUserInfo, iot_device_linkage_condition req)
        {

            EFYihongIotContext ef = new EFYihongIotContext();


            iot_device_linkage linkage = ef.iot_device_linkage.Where(c => c.l_guid == req.lc_l_guid).FirstOrDefault();

            iot_device_linkage_condition LastLinkageCondition = (from l in ef.iot_device_linkage
                                                                 join c in ef.iot_device_linkage_condition on l.l_guid equals c.lc_l_guid
                                                                 where l.l_p_guid == linkage.l_p_guid && c.lc_p_model_no != null
                                                                 select c).OrderByDescending(c => c.lc_p_model_no).FirstOrDefault();




            //先查一下有没重复提交
            iot_device_linkage_condition model = ef.iot_device_linkage_condition.Where(c => c.lc_guid == req.lc_guid).FirstOrDefault();
            if (model == null)
            {

                //查询orderno+1
                int orderNo = 1;
                iot_device_linkage_condition modelorderby = ef.iot_device_linkage_condition.Where(c => c.lc_l_guid == req.lc_l_guid).OrderByDescending(c => c.lc_order).FirstOrDefault();
                if (modelorderby != null)
                {
                    orderNo = modelorderby.lc_order + 1;
                }
                req.lc_order = orderNo;

                //写入
                if (req.lc_operation == "main")
                {
                    if (!string.IsNullOrWhiteSpace(req.lc_vr_guid))
                    {
                        req.lc_value_rule = new DBIotDeviceVariableValueRlueCache().getVariableValueRlueListByCache().Where(c => c.vr_guid == req.lc_vr_guid).FirstOrDefault().vr_rule;
                    }
                    req.lc_key = new DBIotDeviceVariableCache().getVariableListByCache().Where(c => c.v_guid == req.lc_dv_guid).FirstOrDefault().v_key;
                    iot_device_model_variable variable = new DBIotDeviceVariableCache().getVariableByKeyCache(req.lc_key);
                    if (variable != null)
                    {
                        //if (variable.v_value_type == "string" || variable.v_value_type == "bool")
                       // {
                        //    req.lc_value_rule = variable.;
                        //}
                        req.lc_dv_guid = variable.v_guid;
                    }
                }
                else if (req.lc_operation == "follow")
                {

                    req.lc_key = new DBIotDeviceCommand().getCommand(req.lc_dc_guid).dc_key;
                    //  req.lc_value = req.lc_key;
                   // if (req.lc_value_rule == null)
                   // {
                        //iot_device_model_variable variable = new ServiceIotDeviceVariableCache().getVariableByKey(req.lc_key);
                       // if (variable != null)
                       // {
                          //  req.lc_dv_guid = variable.v_guid;
                       // }
                   // }
                }


                if (LastLinkageCondition != null && LastLinkageCondition.lc_p_model_no != null)
                {
                    req.lc_p_model_no = LastLinkageCondition.lc_p_model_no + 1;
                }
                else
                {
                    req.lc_p_model_no = 1;
                }
                req.lc_add_time = DateTime.Now;
                req.lc_mod_time = DateTime.Now;
                ef.iot_device_linkage_condition.Add(req);
                ef.SaveChanges();
            }
            else
            {

                if (req.lc_operation == "main")
                {
                    if (!string.IsNullOrWhiteSpace(req.lc_vr_guid))
                    {
                        model.lc_value_rule = new DBIotDeviceVariableValueRlueCache().getVariableValueRlueListByCache().Where(c => c.vr_guid == req.lc_vr_guid).FirstOrDefault().vr_rule;
                    }
                    model.lc_key = new DBIotDeviceVariableCache().getVariableListByCache().Where(c => c.v_guid == req.lc_dv_guid).FirstOrDefault().v_key;
                    iot_device_model_variable variable = new DBIotDeviceVariableCache().getVariableByKeyCache(req.lc_key);
                    if (variable != null)
                    {
                        if (variable.v_value_type == "string" || variable.v_value_type == "bool")
                        {
                            req.lc_value_rule = "=";
                        }
                        req.lc_dv_guid = variable.v_guid;
                    }
                }
                else if (req.lc_operation == "follow")
                {
                    model.lc_key = new DBIotDeviceCommand().getCommand(req.lc_dc_guid).dc_key;
                    req.lc_value = req.lc_key;
                    if (req.lc_value_rule == null)
                    {
                        iot_device_model_variable variable = new DBIotDeviceVariableCache().getVariableByKeyCache(req.lc_key);
                        if (variable != null)
                        {
                            req.lc_dv_guid = variable.v_guid;
                        }
                    }
                }
                if (LastLinkageCondition != null && LastLinkageCondition.lc_p_model_no != null)
                {
                    req.lc_p_model_no = LastLinkageCondition.lc_p_model_no + 1;
                }
                else
                {
                    req.lc_p_model_no = 1;
                }
                model.lc_repeat_count = req.lc_repeat_count;
                model.lc_repeat_interval = req.lc_repeat_interval;
                model.lc_d_guid = req.lc_d_guid;
                model.lc_operation = req.lc_operation;
                model.lc_dv_guid = req.lc_dv_guid;
                model.lc_value = req.lc_value;
                model.lc_vr_guid = req.lc_vr_guid;
                ef.iot_device_linkage_condition.Update(model);
                ef.SaveChanges();
            }
            return true;
        }

        public List<Dictionary<string, string>> getEditConitionItemList(HttpReqModel httpReqModel, string operation)
        {
            EFYihongIotContext ef = new EFYihongIotContext();
            List<iot_device_linkage_condition> iot_Device_Linkage_Conditions = ef.iot_device_linkage_condition.Where(c => c.lc_l_guid == httpReqModel.guid).OrderBy(c => c.lc_order).ThenBy(c => c.lc_id).ToList();

            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
            List<iot_device> devices = new DBIotDevice().getClientDeviceList();
            List<iot_device_model_variable> iot_Device_Variables = new DBIotDeviceVariableCache().getVariableListByCache();
            List<iot_device_model_variable_value_rlue> value_Rlues = new DBIotDeviceVariableValueRlueCache().getVariableValueRlueListByCache();

            foreach (iot_device_linkage_condition item in iot_Device_Linkage_Conditions.Where(c => c.lc_operation == operation).ToList())
            {
                Dictionary<string, string> directory = new Dictionary<string, string>();

                directory.Add("lc_guid", item.lc_guid);
                directory.Add("name", devices.Where(c => c.d_guid == item.lc_d_guid).FirstOrDefault().d_name);
                if (item.lc_dc_guid != null)
                {
                    directory.Add("dcname", new DBIotDeviceCommand().getCommand(item.lc_dc_guid).dc_name);
                }
                else
                {
                    directory.Add("dcname", "");
                }
                if (operation == "main")
                {
                    if (item.lc_dv_guid != null)
                    {
                        directory.Add("dvname", iot_Device_Variables.Where(c => c.v_guid == item.lc_dv_guid).FirstOrDefault().v_name);
                    }
                    else
                    {
                        directory.Add("dvname", "");
                    }
                }
                if (!string.IsNullOrEmpty(item.lc_vr_guid))
                {
                    directory.Add("vrname", value_Rlues.Where(c => c.vr_guid == item.lc_vr_guid).FirstOrDefault().vr_name);
                }
                else
                {
                    directory.Add("vrname", "");
                }
                directory.Add("lc_repeat_count", item.lc_repeat_count.ToString());
                directory.Add("lc_repeat_interval", item.lc_repeat_interval.ToString());
                directory.Add("value", item.lc_value);
                list.Add(directory);
            }
            return list;
        }

    }
}
